package com.atguigu.eduservice.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.excel.EasyExcel;
import com.atguigu.eduservice.entity.EduSubject;
import com.atguigu.eduservice.entity.excel.OneSubject;
import com.atguigu.eduservice.entity.excel.TwoSubject;
import com.atguigu.eduservice.listener.DemoDataListener;
import com.atguigu.eduservice.mapper.EduSubjectMapper;
import com.atguigu.eduservice.service.EduSubjectService;
import com.atguigu.entity.DemoData;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**

 */
@Service
public class EduSubjectServiceImpl extends ServiceImpl<EduSubjectMapper, EduSubject> implements EduSubjectService {

	@Resource
	private EduSubjectService eduSubjectService;


	@Override
	public void saveExcels(MultipartFile multipartFile, EduSubjectService eduSubjectService) {
		//1 获取文件输入流
		try {
			InputStream inputStream = multipartFile.getInputStream();
			EasyExcel.read(inputStream, DemoData.class, new DemoDataListener(eduSubjectService)).sheet().doRead();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

	@Override
	public List<OneSubject> getAllOneAndTwo() {
		LambdaQueryWrapper<EduSubject> lambdaOne=new LambdaQueryWrapper<>();
		//查询getParentId=0的数据
		lambdaOne.eq(EduSubject::getParentId,0);
		List<EduSubject> eduOneSubjects = this.list(lambdaOne);

		LambdaQueryWrapper<EduSubject> lambdaTwo = new LambdaQueryWrapper<>();
		//查询getParentId!=0的数据
		lambdaTwo.notIn(EduSubject::getParentId, 0);
		List<EduSubject> EduTwoSubjects = this.list(lambdaTwo);

		/**
		 *将twoSubject中的数据拷贝到oneSubject中
		 */
		List<OneSubject> oneSubjects = new ArrayList<>();
		//封装一级分类
		for (int i = 0; i < eduOneSubjects.size(); i++) {
			EduSubject eduSubject = eduOneSubjects.get(i);
			OneSubject finalOneSubject;

			/*finalOneSubject.setId(eduSubject.getId());
			finalOneSubject.setName(eduSubject.getTitle());*/

			//oneSubjects.add(finalOneSubject);
			//封装二级分类
			finalOneSubject = BeanUtil.copyProperties(eduSubject, OneSubject.class);

			List<TwoSubject> copyTwoSubject = new ArrayList<>();
			for (int j = 0; j < EduTwoSubjects.size(); j++) {
				EduSubject twoeduSubject = EduTwoSubjects.get(j);
				//将TwoEduSubject拷贝到twoSubject中
				if (twoeduSubject.getParentId().equals(eduSubject.getId())) {
					TwoSubject finalTwoSubject = BeanUtil.copyProperties(twoeduSubject, TwoSubject.class);
					copyTwoSubject.add(finalTwoSubject);
				}

			}

			finalOneSubject.setList(copyTwoSubject);
			oneSubjects.add(finalOneSubject);

		}

		return oneSubjects;
	}
}
